// ***************************************************************************
// Caution: modifying this file will affect the integrity of the application.
// ***************************************************************************
// Copyright ?1995-2007, Camstar Systems, Inc. All Rights Reserved.
// This file is used for the more common functions 
// Variables pertain only to this file
var mOpenedSelectionList = null;
var mOpenedParentSpan	= null;
var mLowZindex	= top.ZIndexLow;
var mHighZindex	= top.ZIndexHigh;
// The src element that has focus when the enter button is pressed
var mFocusElement = null;

// The default alert text to display when keys have been disabled,
// but InSite is not available to get the alert text.
var mDisabledKeyAlert = "This key has been disabled.";

// The control name where current scroll position are saver on post back
var	mPositionInputName = "__position";

// The saved DoPostBack handler
var mOldDoPostBack = null
var mPostBackInProgress = false
var mDoNextPostBack = false
// For save last postback
var mOldParam1 = null;
var mOldParam2 = null;

var mToolTipLabels = null;

var mkPopupClosedButton = "popupClosedButton";
var mkInstanceList = "FrameworkInstanceList";
var mkInstanceNameBox = "instanceNameBox";
var mkInstanceRevBox = "instanceRevisionBox";
var mkReloadButton   = "reloadButton";
var mkDisabledByDefaultAttribute = "disabledByDefault";
var mkUserFieldsDiv = "userFieldsDiv";
var mkParametricDiv = "parametricDiv";
var mkValidateFunctionName = "OnDCDFieldValueChanged";
var mkKeyCode = "";
// For use with the SetIFrameButtons
var setSingleTimeout = null;

//Defines whether element`s properties allow to focus and click it
function IsElementFocusableClickable(element)
{
    var result = false;
    if (element != null)
    {
        if (!element.disbled && element.style.display.toLowerCase() != top.DisplayStyleNone)
        {
            result = true;
        }//if
    }//if
    return result;
}//IsElementFocusableClickable

//Runs through the document elements with the specified tags and looks for those set as default
//Puts all default elements availeble for input into the array
//Returns array of default elements
function GetDefaultElementsByTagsArray(tagsArray)
{
    var mkLowerCaseTrue = "true";
    var mkDefaultAtt = "IsDefaultButton";
    var mkInFrameAtt = "IsInFrameButton";

    var defaultElements = new Array();
    var defIndex = 0;

    if (tagsArray != null && tagsArray.length > 0)
    {
        //Run through tagsArray
        for (var tagIndex = 0; tagIndex < tagsArray.length; tagIndex++)
        {
            //Get elements of the specified tag
            var elementsArray = document.getElementsByTagName(tagsArray[tagIndex]);
            if (elementsArray != null && elementsArray.length > 0)
            {
                //Loop through the elements
                for ( var i = 0; i < elementsArray.length; i++)
                {
                    //Find default elements
                    var isDefault = elementsArray[i].getAttribute(mkDefaultAtt);
                    if (isDefault != null && isDefault.toLowerCase() == mkLowerCaseTrue)
                    {
                        //Check whether default element is displayed in frame
                        var isInFrame = elementsArray[i].getAttribute(mkInFrameAtt);
                        if (isInFrame != null && isInFrame.toLowerCase() == mkLowerCaseTrue)
                        {
                            if (elementsArray[i].id != null && elementsArray[i].id != "")
                            {
                                var buttonsDocument = parent.document.frames[top.CtrlButtonsIframe].document;
                                if (buttonsDocument != null)
                                {
                                    if (IsElementFocusableClickable(buttonsDocument.all[elementsArray[i].id]))
                                    {
                                        //Add element from the frame into the array of default clickable elements
                                        defaultElements[defIndex] = buttonsDocument.all[elementsArray[i].id];
                                        defIndex += 1;
                                    }//if (IsElementFocusableClickable)
                                }//if (buttonsDocument != null)
                            }//if (id)
                        }//if (isInFrame)
                        else //Element is not in the frame
                        {
                            if (IsElementFocusableClickable(elementsArray[i]))
                            {
                                //Add element into the array of default clickable elements
                                defaultElements[defIndex] = elementsArray[i];
                                defIndex += 1;
                            }//if (IsElementFocusableClickable)
                        }//else
                    }//if (isDefault)
                }//for (elementsArray)
            }//if (elementsArray)
        }//for (tagsArray)
    }//if (tagsArray)
    return defaultElements;
}//GetDefaultElementsByTagsArray

// Set the focus on the button when the enter key is pressed
function SetFocusOnDefaultButton()
{
    var result = true;
    // If the enter key was pressed and we are not in a text area,
    // then set the focus on the button to submit
    if ((event.keyCode == gkEnterKeyCode) && (!IsTextAreaElement()) && (!IsSelectionElement()))
    {
        if ((event.srcElement.type != top.TypeImage.toLowerCase()) && (event.srcElement.type != ''))
        {
            var defaultInputElements = new Array();
            var defaultElementTags = new Array("input", "a", "button");
            defaultInputElements = GetDefaultElementsByTagsArray(defaultElementTags);

            if (defaultInputElements.length == 1)
            {
                defaultInputElements[0].focus();
                defaultInputElements[0].click();
                result = false;
            }//if
            else if (defaultInputElements.length > 1)
            {
                alert ("Default button is ambiguous!");
            }//else if
        }//if
    } // if
    return result;
} // SetFocusOnDefaultButton

// After the cancelSubmit button
function SetFocusOnFocusElement()
{
    if (mFocusElement != null)
    {
        mFocusElement.focus();
    } //if
} // SetFocusPostCancelSubmit

//Function to select menu item on pressing Enter or Space keys
function MenuKeyPressed(controlId)
{
    var ClickKeyList = new Array("13", "32");
    for (var i=0; i<ClickKeyList.length; i++)
    {
        event.cancelBubble = false;
        if (event.keyCode == ClickKeyList[i])
        {
            controlId.fireEvent("onclick");
        }//if
    }//for
}//MenuKeyPressed

// Function to cancel the list of keys pressed by the user
function CancelKeyPress()
{
    var disabledKey = false;
    mkKeyCode = event.keyCode;
    for (var i=0; i<top.CancelKeyPressList.length; i++) 
    { 
        var splitItem = top.CancelKeyPressList[i].split('+');
        if (splitItem.length == 1)
        {
            if (event.keyCode == top.CancelKeyPressList[i])
            {
                // Check to see if it is the backspace
                if ((top.CancelKeyPressList[i] == gkBackSpaceKeyCode) && 
                        (event.srcElement.tagName == "DIV" || event.srcElement.tagName == "INPUT" || event.srcElement.tagName == "TEXTAREA"))
                {
                    // Do not cancel the backspace if the user 
                    // is in a text box, textarea, text editor area or password element.
                    if ((!IsTextElement()) && (!IsTextAreaElement()) && (!IsFileElement()) && (!IsPasswordElement()))
                    {
                        disabledKey = true;
                    } // if
                    else
                    {
                        // Do not cancel the backspace if the user 
                        // is in a text box, textarea or password element
                        // and it`s ReadOnly property is not set to true.
                        if (IsReadOnly())
                        {
                            disabledKey = true;
                        }
                    }
                }
                else
                {
                    disabledKey = true;
                } // if else
            } // if
        }
        else if (splitItem.length == 2)
        {
            // The alt key
            if (splitItem[0] == gkAltKeyCode)
            {
                if (event.altKey)
                {
                    if (event.keyCode == splitItem[1])
                    {
                        disabledKey = true;
                    } // if
                } // if
            }// if
        }// if else

        // Inform the user of the key being disabled
        if (disabledKey)
        {
            event.keyCode = 0;
            event.returnValue = false;
            if (top.InSiteLblDisabledKey != null) 
                alert(top.InSiteLblDisabledKey);
            else 
                alert(mDisabledKeyAlert);
            return false;
        } // if
    } // for
} // CancelKeyPress


// Set the focus on the control with a tab index of 1
function SetFocusOnFirstTabIndex()
{
    SetNewDoPostBackHandler();

    // Use SaveScrollingPosition() function to handle onscroll event
    window.onscroll = SaveScrollingPosition;

    if(((typeof(IsTransactionSuccessful) != 'undefined') && (IsTransactionSuccessful == 'false')) || (typeof(IsTransactionSuccessful) == 'undefined'))
    {
        if(RestoreScrollingPosition())
        {
            // Do not set focus if position has been restored
            return;
        }

        if((typeof(IsPostBackFlag) != 'undefined') && (IsPostBackFlag == 'true'))
        {
            // Do not set focus if postback has been occured
            return;
        }
    }
    
    if (document.forms[0] != null)
    {
        for (var i=0; i<document.forms[0].elements.length; i++) 
        {
            var controlName = document.forms[0].elements[i].name;
            if (controlName != '')
            {
                if (document.forms[0][controlName].tabIndex != null)
                {
                    if (document.forms[0][controlName].tabIndex == 1)
                    {
                        // Attach function to handle bug with window focus
                        document.forms[0][controlName].attachEvent('onkeydown', function()
                        {
                            if (event.keyCode == gkTabKeyTabCode)
                            {
                                // Do not set focus if it is the Shift + Tab
                                if(!event.shiftKey)
                                {
                                    // Set the focus back to the src element which has the tabindex of 1
                                    // This will automatically cause the tab to hit the control with
                                    // a tabindex greater than 1
                                    window.event.srcElement.focus();
                                } // if
                            } // if
                        }
                        );

                        try
                        {
                            // fires OnDeactivate event for existent pickLists.
                            window.focus();
                            document.forms[0][controlName].focus();
                            return false;
                        }
                        catch (e)
                        {
                        }
                    } // if
                } // if
            } // if
        } // for
    } // if
} // SetFocusOnFirstTabIndex

// This function will fix the issue with the grid scrolling during postbacks
function FixGridScrolling(gridId, scrollTopId, scrollLeftId)
{
    var grid = document.getElementById(gridId); 
    var scrollTop = document.getElementById(scrollTopId); 
    var scrollLeft = document.getElementById(scrollLeftId);

    if(grid != null)
    {
        // Attach function to the onscroll event to set the top and left positions of the parent DIV
        grid.parentElement.attachEvent(top.EventOnScroll, function()
            {
                grid.rows[0].style.posTop = grid.parentElement.scrollTop -1; // -1 to offset the spacing/padding
                scrollTop.value = grid.parentElement.scrollTop; // store the scrollTop position of the parent DIV
                scrollLeft.value = grid.parentElement.scrollLeft; // store the scrollLeft position of the parent DIV
            }
        );

        // Set the parent DIV's top / left position based on the passed in values
        grid.parentElement.scrollTop = scrollTop.value;
        grid.parentElement.scrollLeft = scrollLeft.value;
    } // if
} // FixGridScrolling

// Page through the instances by calling the buttons in the instance iframe
function PageInstances(position, iFrameId)
{
    if(iFrameId == '')
    {
        iFrameId = ReplaceStringText(mOpenedSelectionList, top.CtrlSuffixContainer, top.CtrlSuffixSelectionList);
    }// if

    if(document.frames[iFrameId] != null)
    {
        var iFrameDoc = document.frames[iFrameId].document.all;
        if(position == top.PagingTypeFirst)
        {
            iFrameDoc[top.CtrlFirstPageButton].click();
        }
        else if(position == top.PagingTypeNext)
        {
            iFrameDoc[top.CtrlNextPageButton].click();
        }
        else if(position == top.PagingTypePrevious)
        {
            iFrameDoc[top.CtrlPreviousPageButton].click();
        }
        else if(position == top.PagingTypeLast)
        {
            iFrameDoc[top.CtrlLastPageButton].click();
        }// if else
    }
    else
    {
        // Tell the user that there is no iframe on the page by that id
        alert('There is no iframe by that id.');
    } // if else
} // PageInstances

// Set the display for the paging controls
function SetPagingPosition(doDisplay, pagingId, imageSource, imageMap)
{
    if(document.all[pagingId] != null)
    {
        if(doDisplay)
        {
            document.all[pagingId].style.display = top.DisplayStyleBlock;
            document.all[pagingId].src      = imageSource
            document.all[pagingId].useMap   = '#' + imageMap; 
        }
        else
        {
            document.all[pagingId].style.display = top.DisplayStyleNone;
        } // if else
    } // if
} // SetPagingPosition

// Create a new tabbed section for a new CDO
function CreateNewReferencedCDO(CDOType, pageName, pageTitle, serviceType, helpPageName)
{
    // Set the values for the CDO	
    SetCDOValues(CDOType, pageName, pageTitle, serviceType, helpPageName)

    // Create a new tabbed section
    parent.parent.document.all[top.CtrlLoadReferencedInstanceButton].click();
} // CreateNewReferencedCDO

// Load the instance for the referenced CDO
function LoadReferencedCDO(CDOType, pageName, pageTitle, serviceType, helpPageName, instanceNameId, instanceRevId, instanceUseRORId, refreshInstList)
{
    // Set the values of the instance	
    SetCDOValues(CDOType, pageName, pageTitle, serviceType, helpPageName)

    // Set the instance values
    SetInstanceValues(instanceNameId, instanceRevId, instanceUseRORId, refreshInstList)

    // Create a new tabbed sectionFalert
    parent.parent.document.all[top.CtrlLoadReferencedInstanceButton].click();
} // LoadReferencedCDO

// Set the instance values
function SetInstanceValues(instanceNameId, instanceRevId, instanceUseRORId, refreshInstList)
{
    // Set the instance values on the parent page
    parent.parent.document.all[top.CtrlInstanceNameHidden].value = GetTextValue(instanceNameId);
    parent.parent.document.all[top.CtrlInstanceRevHidden].value = GetTextValue(instanceRevId);
    parent.parent.document.all[top.CtrlInstanceUseRORHidden].value = GetCheckedValue(instanceUseRORId);
    parent.parent.document.all[top.CtrlRefreshInstListHidden].value = refreshInstList;
} // SetInstanceValues

// Set the CDO values
function SetCDOValues(CDOType, pageName, pageTitle, serviceType, helpPageName)
{
    // Set the CDO values on the parent page
    parent.parent.document.all[top.CtrlCDOTypeHidden].value = CDOType;
    parent.parent.document.all[top.CtrlPageNameHidden].value = pageName;
    parent.parent.document.all[top.CtrlPageTitleHidden].value = pageTitle;
    parent.parent.document.all[top.CtrlServiceTypeHidden].value = serviceType;
    parent.parent.document.all[top.CtrlHelpPageNameHidden].value = helpPageName;
} // SetCDOValues

// Given an id get the value for the text input
function GetTextValue(textId)
{
    // Is it a valid object
    if(gDoc[textId] != null)
    {
        return gDoc[textId].value;
    }
    else
    {
        return null;
    } // if else
} // GetTextValue

// Given an id get the value for the checkbox input
function GetCheckedValue(textId)
{
    // Is it a valid object
    if(gDoc[textId] != null)
    {
        return gDoc[textId].checked;
    }
    else
    {
        return null;
    } // if else
} // GetCheckedValue

// Pass in the filter value and the the id of the iframe that contains the instance.
// Set the filter value on the form in the iframe and then cause the click event for
// the button on the iframe, causing the filter to happen server side without resetting 
// the iframe source
function FilterInstances(filterValue, instanceIframeId)
{
    if(document.frames[instanceIframeId] != null)
    {
        // Set the value
        document.frames[instanceIframeId].document.all[top.CtrlFilterValueTextBox].value = filterValue;

        // Retreive the instances
        document.frames[instanceIframeId].document.all[top.CtrlFilterInstancesButton].click(); 
    } 
    else
    {
        // Tell the user that there is no page name
        alert('FilterInstances - There is no iframe that exists by the id = ' + instanceIframeId);		
    } // if else
} // FilterInstances

// Determines if we are currently on a text element.
function IsTextElement()
{
    if (event.srcElement.tagName == "INPUT")
    {
        var typeText = "text";
        var srcElementType = event.srcElement.type.toLowerCase();
        if (srcElementType == typeText) 
            return true;
    }
    return false;
} //IsTextElement()

// Determines if we are currently on a text area element (multi-line text box).
function IsTextAreaElement()
{
    var tagTextArea = "textarea";
    var srcElementTagName = event.srcElement.tagName.toLowerCase();
    if (srcElementTagName == tagTextArea) 
        return true;
    else 
        // Spectial test for WebHtmlEditor control
        if(srcElementTagName == "div" && event.srcElement.getAttribute("contentEditable"))
            return true;
    else
        return false;
} //IsTextAreaElement()

// Determines if we are currently on a file element.
function IsFileElement()
{
    var typeFile = "file";
    var srcElementType = event.srcElement.type.toLowerCase();
    if (srcElementType == typeFile) 
        return true;
    else
        return false;
} //IsFileElement()

// Determines if we are currently on a password element.
function IsPasswordElement()
{
    var typePw = "password";
    var srcElementType = event.srcElement.type.toLowerCase();
    if (srcElementType == typePw) 
        return true;
    else
        return false;
} //IsPasswordElement()

// Determines if we are currently on a selection element.
function IsSelectionElement()
{
    var tagSelect = "select";
    var srcElementTagName = event.srcElement.tagName.toLowerCase();
    if (srcElementTagName == tagSelect) 
        return true;
    else
        return false;
} //IsSelectionElement

//Determines if the current element`s readOnly property is set to true
function IsReadOnly()
{
    var TrueReadOnly = true;
    var srcElementReadOnly = event.srcElement.readOnly;
    if (srcElementReadOnly == TrueReadOnly)
        return true;
    else
        return false;
}//IsReadOnly

//Set the display for the paging controls (first, previous, next, last)
function SetPaging (doDisplayAll, isActive, pagingId, pagingImage, pagingGrayImage, pagingUrl, instanceListIframe, tableId)
{
    var pagingTable = document.all[tableId];
    if (pagingTable == null) return;
    var i;
    var pagingLinkList = pagingTable.all.tags("A");
    var pagingLinkObject = null;

    for(i=0; i<=pagingLinkList.length; i++)
    {
        if( pagingLinkList[i].id.indexOf(pagingId) >= 0 )
        {
            pagingLinkObject = pagingLinkList[i];
            break;
        }//if
    }//for

    if(pagingLinkObject != null)
    {
        if (doDisplayAll)
        {
            if (isActive)
            {
                pagingLinkObject.parentElement.parentElement.style.display = top.DisplayStyleBlock;
                pagingLinkObject.children[0].src = pagingImage;
                pagingLinkObject.href = "javascript:PageInstances('" + pagingUrl + "', '" + instanceListIframe + "');";
            }//if (isActive)
            else
            {
                pagingLinkObject.parentElement.parentElement.style.display = top.DisplayStyleBlock;
                pagingLinkObject.children[0].src = pagingGrayImage;
                pagingLinkObject.href = "#";
            }//else
        }//if (doDisplayAll)
    }//if
}//SetPaging

// Saves current window scroll position
function SaveScrollingPosition()
{
    if( document.forms[0] != null )
    {
        var positionInput = document.forms[0].elements[mPositionInputName];
        if( positionInput != null )
        {
            positionInput.value = document.body.scrollLeft + "," + document.body.scrollTop;
            var userFieldsDiv = document.all[mkUserFieldsDiv]
            if (userFieldsDiv!=null)
                positionInput.value += ("," + userFieldsDiv.scrollLeft+ "," + userFieldsDiv.scrollTop);
            else
                positionInput.value += ",0,0";
            var parametricDiv = document.all[mkParametricDiv]
            if (parametricDiv!=null)
                positionInput.value += ("," + parametricDiv.scrollLeft+ "," + parametricDiv.scrollTop);
            else
                positionInput.value += ",0,0";
        }
    }
} // SaveScrollingPosition

// Restores window scroll position after post-back
// Returns true if scroll position is not at (0,0) and false otherwise
function RestoreScrollingPosition()
{
    var hasScrolling = false;
    if( document.forms[0] != null )
    {
        var positionInput = document.forms[0].elements[mPositionInputName];
        if( positionInput != null )
        {
            if( positionInput.value.length > 0 )
            {
                var	position = positionInput.value.split(',')
                if( position.length == 6 )
                {
                    var	myPageX = position[0];
                    var	myPageY = position[1];
                    window.scrollTo(myPageX,myPageY);
                    if( myPageX > 0 || myPageY > 0 ) hasScrolling = true;

                    var userFieldsDiv = document.all[mkUserFieldsDiv]
                    if (userFieldsDiv!=null)
                    {
                        userFieldsDiv.scrollTop = position[3];
                        userFieldsDiv.scrollLeft = position[2];
                    }
                    var parametricDiv = document.all[mkParametricDiv]
                    if (parametricDiv!=null)
                    {
                        parametricDiv.scrollTop = position[5];
                        parametricDiv.scrollLeft = position[4];
                    }
                }
            }
        }
    }
    return hasScrolling;
} // RestoreScrollingPosition

// Opens modal or modeless popup window
function OpenPopupWindow(isModeless, popupPageName, popupPageProperties)
{
    //var pageInstanceId = 'PageInstanceId' + ReturnPageInstanceId();

    var params = new Array();
    params[0] = window;
    params[1] = isModeless;

    try
    {
        var retVal = window.showModalDialog(popupPageName+"?v="+new Date().getTime(), params, popupPageProperties);
        if (retVal == true) {
            $("input[id$=" + mkPopupClosedButton + "]").click();
            //window.setTimeout('OnPopupWindowClosed()', 100);
        }
    }
    catch(e)
    {
        alert("Can't open the following url:\n\"" + popupPageName + "\"");
    }
} // OpenPopupWindow

// Open independent window
function OpenIndependentWindow(pageName, pageProperties, resetParentFocus, intervalToSync)
{
    try
    {
        if(resetParentFocus)
            SetFocusOnFirstTabIndex();
    
        var mainWindow = window.parent.parent.parent;
        if(mainWindow)
        {
            pageName = pageName + '&' + top.QueryStringPageInstanceId + '=' + ReturnPageInstanceId(); 
            var popupWindow = window.open(pageName, "_blank", pageProperties);
            if(popupWindow)
            {
                if(mainWindow.mChildIndependentWindows)
                    mainWindow.mChildIndependentWindows[mainWindow.mChildIndependentWindows.length] = popupWindow;

                // Every time specified in "intervalToSync" the opened window will check the parent window "close" property.
                // If the parent window is closed the opened window will be closed too.                
                popupWindow.attachEvent("onload", function() {PrepareOpenedWindow(popupWindow, intervalToSync);});
                
                // Discard the following function to leave the focus on the opened window
                SetFocusOnFirstTabIndex = function()
                {
                }
            }
        }
    }
    catch(e)
    {
        alert("Can't open the following url:\n\"" + pageName + "\"");
    }
} // OpenIndependentWindow

// Register calling of "SyncWithOpener()" fucntion if the opened independent window's url have been found and loadedl.
function PrepareOpenedWindow(childWindow, intervalToSync)
{
    if(childWindow)
    {
        if(childWindow.document.title != "The resource cannot be found.")
        {
            childWindow.setInterval("SyncWithOpener()", intervalToSync);
        }
    }
} // PrepareOpenedWindow

// Close the "independent" window when the parent already is closed.
function SyncWithOpener()
{
    if(opener)
        if(opener.closed == true)
            window.close();
} // SyncWithOpener

// Notifies parent window of popup closed
function NotifyParentOfPopupClosed()
{
    if (window.dialogArguments != null)
    {
        if (window.dialogArguments[0].document.all[mkPopupClosedButton] != null)
            window.dialogArguments[0].document.all[mkPopupClosedButton].click();
        // Modal dialog response
        if (window.dialogArguments[1] == false) 
        {
            window.returnValue = true;
        } 
        // Modeless dialog response
        else 
        {
            if (window.dialogArguments[0].document.all[mkPopupClosedButton] != null)
                window.dialogArguments[0].document.all[mkPopupClosedButton].click();
        }
    }
    else
    {
        // Independent window response
        if(window.opener)
            if(window.opener.document.all[mkPopupClosedButton] != null)
                window.opener.document.all[mkPopupClosedButton].click();
    }
} // NotifyParentOfPopupClosed

// Performs popupClosedButton click if popup window requires parent notification
function OnPopupWindowClosed()
{
    if (document.all[mkPopupClosedButton] != null)
    {
        document.all[mkPopupClosedButton].click();
    }
} // OnPopupWindowClosed

// Evokes instance list`s reload
function ReloadInstanceList(instanceName, instanceRev)
{
    //Get Instance List client object
    var instanceList = parent.getPickListById(mkInstanceList);
    if (instanceList != null )
    {
        //Find text controls for the name and revision of the active instance
        var instanceNameBox = parent.document.getElementById(instanceList.filterCtrlId + '_' + mkInstanceNameBox);
        var instanceRevBox = parent.document.getElementById(instanceList.filterCtrlId + '_' + mkInstanceRevBox);
        if (instanceNameBox != null && instanceRevBox != null)
        {
            if (instanceName == "")
            {
                //Empty instance name means that instance was deleted
                //Set it equal to the tag delimeter to let the server know about deleting
                instanceName = encodeURIComponent(top.PickListTagDelimiter);
            }//if
            //Put instance name and revision into the correcponding controls
            instanceNameBox.value = instanceName;
            instanceRevBox.value = ((instanceRev != null) ? instanceRev : "");
            //Click Filter button to evoke instance list refresh and reload
            instanceList.FilterClick();
        }//if
    }//if
} // ReloadInstanceList

// Sets up new postback handler
function SetNewDoPostBackHandler()
{
    try{
        if (__doPostBack != null && mOldDoPostBack==null)
        {
            mOldDoPostBack = __doPostBack;
            __doPostBack = NewDoPostBack;
        }
    }
    catch(e){}
} // SetNewDoPostBackHandler


// The new postback handler
function NewDoPostBack(Param1, Param2)
{
    //Does not submit multiple postbacks
    if( ! mPostBackInProgress) 
    {
        mPostBackInProgress = true;
        // Save postback
        mOldParam1 = Param1;
        mOldParam2 = Param2;
        mOldDoPostBack(Param1, Param2);
        // Reset flag in one second
        window.setTimeout("mPostBackInProgress=false;" +
        "if(mDoNextPostBack) { mDoNextPostBack = false;" +
        "NewDoPostBack(mOldParam1, mOldParam2); }", 1000);
    }
    else if(mOldParam1 != Param1)
    {
        // Save postback
        mOldParam1 = Param1;
        mOldParam2 = Param2;
        mDoNextPostBack = true;
    }
} //NewDoPostBack

// Locks or unlocks buttons in the bottom frame and in the main frame to prevent clicking on them
//  while popup window is active
function LockButtonsWhilePopup(isLocked)
{

    var buttonsDocument = null;

    if (parent!=null)
        if (parent.document.frames[top.CtrlButtonsIframe] != null)
        {
            buttonsDocument = parent.document.frames[top.CtrlButtonsIframe].document;
            if (buttonsDocument!=null)
                LockButtonsInDocument(isLocked, buttonsDocument);
        }//if
    if (document!=null)
        LockButtonsInDocument(isLocked, document);
}//LockUnlockBottomButtons

// Locks buttons and links (<a> elements) of specified document
function LockButtonsInDocument(isLocked, doc)
{
    var i, elementIndex;
    // Get all buttons, select, table and <a> elements 
    var allElements = new Array(doc.getElementsByTagName("select"), doc.getElementsByTagName("table"), doc.getElementsByTagName("button"), doc.getElementsByTagName("a"), doc.getElementsByTagName("input"));
    for(elementIndex=0; elementIndex<allElements.length; elementIndex++)
    {
        var elements = allElements[elementIndex];
        for(i=0; i<elements.length; i++)
        {
            var buttonElement = elements[i];

            // Ignore PopupClosedButton and hidden and text buttons
            if (buttonElement.tagName=="INPUT")
            {
                if(((buttonElement.type=="button") || (buttonElement.type=="submit")) &&
                    buttonElement.id == mkPopupClosedButton) 
                    continue;
                if (buttonElement.type =="password" || buttonElement.type=="hidden" || buttonElement.type=="text" || buttonElement.type=="checkbox" || buttonElement.type=="radio")
                    continue;
            }
            else
                if (buttonElement.tagName == "TABLE")
                {
                    // Only grid tables are involved.
                    var processTable = false;
                    if (buttonElement.id != null)
                        if (buttonElement.id.indexOf("_main") == buttonElement.id.length-5)
                            processTable = true;
                    if (!processTable)
                        continue;
                }

            var disabledAttributeObj = buttonElement.getAttribute(mkDisabledByDefaultAttribute);
            if (isLocked==true)
            {
                // If the button was previously locked by default and it's being locked then set default attribure
                if (buttonElement.disabled)
                    buttonElement.setAttribute(mkDisabledByDefaultAttribute, "");

                buttonElement.disabled = isLocked;
            }
            else
            {
                buttonElement.disabled = isLocked;
                // If the button was previously locked by default and it's being unlocked then remove attribure
                if (disabledAttributeObj!=null)
                {
                    buttonElement.removeAttribute(mkDisabledByDefaultAttribute);
                    buttonElement.disabled = true;
                }
            }
            
        }// for all buttons
    } // for all element sets
} // LockButtonsInDocument

// Set the buttons after the page has loaded
function SetIFrameButtons(pageInstanceId)
{
    // Clear the timeout and set to null or it will cause an error
    if (setSingleTimeout) {
        clearTimeout(setSingleTimeout);
        setSingleTimeout = null;
    } // if

    // Check to see if the document is in a complete state
    if (parent.document.frames.pageIframe != null)
    {
        if (parent.document.frames.pageIframe.document.readyState != 'complete')
        {
            setSingleTimeout = setTimeout('SetIFrameButtons(\'' + pageInstanceId + '\')', 500);
        } 
        else 
        {
            // Set the location for the buttonsIframe
            var buttonsPage;
            if (parent.location.pathname.indexOf(top.PageWorkingSectionShopFloorTab)!=-1)
                buttonsPage = top.PageWorkingSectionShopFloorTabButtons;
            else
                buttonsPage = top.PageWorkingSectionShopFloorButtons;
            parent.document.frames.buttonsIframe.location = buttonsPage + '?' + top.QueryStringPageInstanceId + '=' + pageInstanceId; 
        } // if else
    }
    else
    {
        setSingleTimeout = setTimeout('SetIFrameButtons(\'' + pageInstanceId + '\')', 500);
    }
} // SetIFrameButtons

//Checks if "parent" element is a parent of the "child" element
function IsElementChildOf(child, parent)
{
    if (child.parentElement != null)
    {
        if (child.parentElement == parent)
        { 
            return true;
        }//if
        else
        {
            return IsElementChildOf(child.parentElement, parent)
        }//else
    }//if
    else
    {
        return false;
    }//if
}//IsElementChildOf

function SwitchImages(event, trueImageSrc, falseImageSrc, checkControlId, autoPostBack)
{
    if (IsValidElement(document, checkControlId))
    {
        var checkControl = gDoc[checkControlId];
        
        if (autoPostBack != 'true')
        {
        if (checkControl.checked)
        {
            event.srcElement.src = falseImageSrc;
        }//if
        else
        {
            event.srcElement.src = trueImageSrc;
        }//else
        }//if
        checkControl.click();
    }//if
}//SwitchImages


//Assign tooltip for control in user data collection definition
function LoadToolTips(dataPontID, toolTipControls)
{
    for(var i=0; i<toolTipControls.length; i++)
    {
        var id = dataPontID + "_"+toolTipControls[i];
        var el = document.all[id];
        if(el != null)
            el.setExpression("title", "CreateToolTip('" + id +"')");
    }
    if (mToolTipLabels == null)
    {
        mToolTipLabels = new Array();
        for(var i=0; i<3; i++)
            mToolTipLabels[i] = document.getElementById(ToolTipLabelControls[i]);
    }   
}//LoadToolTips

//Dynamicaly create tooltip for control in user data collection definition
function CreateToolTip(elementId)
{
    var toolTip = "";
    
    var element = document.getElementById(elementId);
    if(element!=null)
    {
        if(element.UOM != null && mToolTipLabels[0] != null)
        {
            toolTip = mToolTipLabels[0].innerText + ":" + element.UOM;
        }
        if(element.LowerLimit != null && mToolTipLabels[1]!=null)
        {
            toolTip += ("\n" + mToolTipLabels[1].innerText + ":" + element.LowerLimit);
        }
        if(element.UpperLimit != null && mToolTipLabels[2]!=null)
        {
            toolTip += ("\n" + mToolTipLabels[2].innerText + ":" + element.UpperLimit);
        }        
    }//if
    return toolTip;
}//CreateToolTip

// The method is event handler used for InterationGrid PDD control. 
// It is invoked when text box with number (int, float, dec, fixed) inside is changed. 
// The method verifies the value and if the value is out of the limits the background color is switched.
// The colors are defined in the CSS classes.
// The method is also invoked to revalidate related data points if the Is Limit Override check box is being clicked.
// Parameters:
//     string lowerLimit, upperLimit   - value limits;
//     bool   isLimitOverrideAllowed   - true if the the value can be out of the limits. 
//     int    layoutMode               - current dataPointSummary rendering mode: 
//                                      1- IterationGrid; 2 - RowColumn; 0 - validation disabled.
//     string valueType                - type of validated value
function OnDCDFieldValueChanged(lowerLimit, upperLimit, isLimitOverrideAllowed, layoutMode, valueType)
{
    if(event.srcElement != null)
    {
        var inputElement = event.srcElement;
        if (valueType== null)
        {
            // The Override value checkbox was clicked.
            var sampleRow = GetSampleRow(inputElement);
            if (sampleRow == null)
                return;
                
            var inputs = sampleRow.getElementsByTagName("INPUT");
                for(var j=0; j<inputs.length; j++)
                {
                    if (inputs[j].type == "text")
                    {
                        if (inputs[j].onchange != null)
                            if (inputs[j].onchange.toString().indexOf(mkValidateFunctionName)>=0)
                            {
                                // The text box onchange event should be fired.
                                inputs[j].fireEvent("onchange");
                            }
                    }
                    else if (inputs[j].type == "checkbox")
                    {
                        if (inputs[j].onclick != null)
                            if (inputs[j].onclick.toString().indexOf(mkValidateFunctionName)>=0 && inputs[j] != inputElement)
                            {
                                // The text box onchange event should be fired.
                                inputs[j].fireEvent("onclick");
                            }
                    }
                }
            inputs = sampleRow.getElementsByTagName("SELECT");
            for(var j=0; j<inputs.length; j++)
            {
                if (inputs[j].onchange != null)
                    if (inputs[j].onchange.toString().indexOf(mkValidateFunctionName)>=0 && inputs[j] != inputElement)
                    {
                        // The text box onchange event should be fired.
                        inputs[j].fireEvent("onchange");
                    }
            }
        }
        else
        {            
            var isCompositeLimitOverrideAllowed = isLimitOverrideAllowed
            if (layoutMode == 1 || layoutMode == 2)
            {
                // Find checkbox IsOverrideAllowed for Iteration Grid           
                var sampleRow = GetSampleRow(inputElement);                
                var ovrctl = GetOverrideEnableControl(sampleRow); 
                if (ovrctl != null)
                        isCompositeLimitOverrideAllowed = (ovrctl.checked && isLimitOverrideAllowed);
            }
            else
                return;

            // This is a comparison itself
            var currentValue = inputElement.value;
            if (valueType != "String" && valueType != "Boolean")
            {
                // Numeric validation
                currentValue = parseFloat(currentValue);
                if(isNaN(currentValue) && inputElement.value != "")
                {
                    inputElement.className = "TextMediumError";
                }
                else
                {
                    if (lowerLimit != null)
                        lowerLimit = parseFloat(lowerLimit);
                    if (upperLimit != null)
                        upperLimit = parseFloat(upperLimit);
                    if(((lowerLimit == null) || (lowerLimit != null && currentValue >= lowerLimit)) &&
                       ((upperLimit == null) || (upperLimit != null && currentValue <= upperLimit)) ||
                       (event.srcElement.value == ""))
                    {
                        inputElement.className = "TextMedium";
                    }
                    else
                    {
                        inputElement.className = isCompositeLimitOverrideAllowed ? "TextMediumWarning" : "TextMediumError";
                    }
                }
             }
             else if (valueType == "Boolean")
             {
                var boolValue = null;
                var isElementCheckBox = (inputElement.tagName == "INPUT");
                if (! isElementCheckBox )
                {
                    var selectedValue = inputElement.value;
                    if (selectedValue == "1") 
                        boolValue = "true";
                    else 
                        if (selectedValue == "0" ) 
                            boolValue = "false";
                }
                else
                {
                    boolValue = inputElement.checked ? "true" : "false";
                }
                var violation = false;
                if (boolValue!=null && lowerLimit != null && upperLimit!=null)
                {
                    lowerLimit = lowerLimit.toLocaleLowerCase();
                    upperLimit = upperLimit.toLocaleLowerCase();

                    if (lowerLimit == "1") lowerLimit = "true";
                    else if (lowerLimit == "0" ) lowerLimit = "false";

                    if (upperLimit == "1") upperLimit = "true";
                    else if (upperLimit == "0") upperLimit = "false";

                    if(lowerLimit == upperLimit)
                        violation = (boolValue != lowerLimit);
                }
                if (! violation)
                {
                    if (isElementCheckBox)
                    inputElement.className = "Checkbox";
                    else
                        inputElement.className = "SelectMedium"
                }
                else
                {
                    if (isElementCheckBox)
                    inputElement.className = isCompositeLimitOverrideAllowed ? "CheckboxWarning" : "CheckboxError";
                    else
                        inputElement.className = isCompositeLimitOverrideAllowed ? "SelectMediumWarning" : "SelectMediumError";
                }
             }
             else 
             {
                // String validation
                var stringValue = currentValue.toLocaleLowerCase();
                
                if(((lowerLimit == null) || (lowerLimit != null && stringValue.localeCompare(lowerLimit)>=0)) &&
                   ((upperLimit == null) || (upperLimit != null && stringValue.localeCompare(upperLimit)<=0)) ||
                   stringValue.length==0)
                {
                    event.srcElement.className = "TextMedium";
                }
                else
                {
                    event.srcElement.className = isCompositeLimitOverrideAllowed ? "TextMediumWarning" : "TextMediumError";
                }
             }
         }
    }
} //OnDCDFieldValueChanged

// Provides initial validation of data points after post backs.
// Parameters:
//       dataPointID   - ID of dataPoint control
//       initArray     - is the array of pairs of control ID and its event. 
function InitDataPointValidation(dataPointID, initArray)
{
    for(var i=0; i<initArray.length; i+=2)
    {
        var id = dataPointID + "_"+ initArray[i];
        var eventName = initArray[i+1];
        var validatedControl = null;
        
        // Search for the control
        var parentObj = document.all[id];
        var fired = false;
        if (parentObj != null)
        {
            var inputObjs = parentObj.getElementsByTagName("input");
            for(var j=0; j<inputObjs.length; j++)
            {
                var obj = inputObjs[j];
                if (eventName == "OnChange")
                {
                    if(obj.onchange != null)
                        if (obj.onchange.toString().indexOf(mkValidateFunctionName) >= 0 )
                        {
                            obj.fireEvent(eventName);
                            fired = true;
                            break;
                        }
                }
                else if (eventName == "OnClick")
                {
                    if(obj.onclick != null)
                        if (obj.onclick.toString().indexOf(mkValidateFunctionName) >= 0 )
                        {
                            obj.fireEvent(eventName);
                            fired = true;
                            break;
                        }
                }
            }

            if (!fired)
            {
                var selectObjs = parentObj.getElementsByTagName("select");
                for(var j=0; j<selectObjs.length; j++)
                {
                    var obj = selectObjs[j];
                    if (eventName == "OnChange")
                    {
                        if(obj.onchange != null)
                            if (obj.onchange.toString().indexOf(mkValidateFunctionName) >= 0 )
                            {
                                obj.fireEvent(eventName);
                                break;
                            }
                    }
                }
            }
        }
    }
} // InitDataPointValidation

// Finds the sample <tr> element in case of IterationGrid or <table> for RowColumn mode.
// Parameter:
//      fromElement - the INPUT or SELECT element that belongs to PDD control.
function GetSampleRow(fromElement)
{
    var parent = null;
    for (var parent = fromElement.parentElement; parent != null; parent = parent.parentElement)
    {
        if (parent.getAttribute("PDDSample")!=null)
            break;
    }
    return parent;
} //GetSampleRow

// Returns isOverrideLimits checkbox element of PDD control.
// Parameter:
//      sampleRow   - the <tr> or <table> container element.
function GetOverrideEnableControl(sampleRow)
{
    var inputObjs = sampleRow.getElementsByTagName("INPUT");
    for(var i=0; i<inputObjs.length; i++)
    {
        if (inputObjs[i].type == "checkbox" && inputObjs[i].id.indexOf("DataPoint_IsLimitOverride")!=-1)
            return inputObjs[i];
    }
    return null;
} //GetOverrideEnableControl

//Initializes DateChooser control
//Overrides it`s ToDate function to insert current year in case it is not entered
    function NewDateChooserInit(id,p,df,ce,calID)
    {
        OldDateChooserInit(id,p,df,ce,calID);

        var chooser = igdrp_getComboById(id);
        var oldToDate = chooser.editor.toDate;

        chooser.editor.toDate = function(text, inv)
        {
            var result = oldToDate.call(chooser.editor, text, inv);
            if (result == null)
            {
                if (text != null)
                {
                    if(text != "")
                    {
                        var length = text.length;
                        var year = -1, month = -1, day = -1, part = 0, i = -1, f = 0;
                        while(++i <= length)
                        {
                            var textChar = (i < length) ? text.charCodeAt(i) : chooser.editor.sep;
                            if(textChar == chooser.editor.sep)
                            {
                                switch((chooser.editor.order>>part*3)&3)
                                {
                                    case 1:
                                        day=f;
                                        break;

                                    case 2:
                                        month=f;
                                        break;

                                    case 3:
                                        year=f;
                                        break;
                                }//switch
                                part++;
                            }//if
                            textChar -= 48;
                            if(textChar >= 0 && textChar <= 9) f = f*10 + textChar;
                            else f = 0;
                        }//while

                        //If year was not entered
                        if (month > 0 && day > 0)
                        {
                            var curDate = new Date();
                            var newDate = new Date(curDate.getFullYear(), month - 1, day);
                            result = newDate;
                        }//if
                    }//if
                }//if
            }//if
            return result;
        }// ToDate function
    }//NewDateChooserInit

// It is part of creating file upload control
// Hides button from inputLevel1 file control so that user could see our image
function AdjustFileInputWidth(ctrlId, fileCtrlSuffix, childTblLevel3Id)
{
    var divLevel1 = document.getElementById(ctrlId + "_DivLevel1");
    var inputLevel1 = document.getElementById(ctrlId + "_" + fileCtrlSuffix);
    var divLevel2 = document.getElementById(ctrlId + "_DivLevel2");
    var inputLevel3Empty = document.getElementById(ctrlId + "_" + fileCtrlSuffix + "_Level3");

    if (divLevel1 == null || inputLevel1 == null || divLevel2 == null || inputLevel3Empty == null)
        return false;

    var percStart = Math.round((inputLevel1.offsetWidth - inputLevel3Empty.offsetWidth) / inputLevel1.offsetWidth * 100 - 1);
    var percEnd = percStart + 1;

    var strFilter = "alpha(style=1, opacity=100, finishOpacity=0, startX=" + percStart.toString() + ", startY=0, finishX=" + percEnd.toString() + ", finishY=0)";
    inputLevel1.style.filter = strFilter;

    divLevel1.style.height = inputLevel3Empty.offsetHeight + 1;
    divLevel1.style.width = inputLevel1.offsetWidth - inputLevel3Empty.offsetWidth + inputLevel3Empty.offsetHeight + 4;
    divLevel2.style.width = inputLevel1.offsetWidth - inputLevel3Empty.offsetWidth;

    if (childTblLevel3Id != "")
    {
        var childTblLevel3 = document.getElementById(childTblLevel3Id);
        if (childTblLevel3 == null)
            return false;
        childTblLevel3.style.width = inputLevel1.offsetWidth + 3;
    }

}// AdjustFileInputWidth

// Checks Name and Revision fields in maintenance form not to contain disallowed symbols
// bArray and symbolErrString are formed on server side
function checkValue(el)
{
    for (i=0; i<bArray.length; i++)
        if ( el.value.indexOf(bArray[i]) > -1)
        {
            alert(symbolErrString.replace("{0}", "\" " + bArray[i] + " \""));
            el.focus();
            return false;
        }

    return true;
}


function SmartScanResolver(e) {
    if (typeof (smartScanProc) != "undefined") {
        return smartScanProc.ProcessKeyPress(e.charCode != null && e.charCode != 0 ? e.charCode : e.keyCode);
    }
    return true;
}

function SmartScanTabResolver(e) {
    if (typeof (smartScanProc) != "undefined" && e.keyCode == 9) {
        return smartScanProc.ProcessKeyPress(e.keyCode);
    }
    return true;
}

function SmartScanTemplate(_controlId, _prefix, _suffix, _regExp) {
    this.controlId = _controlId;
    this.prefix = _prefix;
    this.suffix = _suffix;
    this.regExpression = _regExp;
    this.zIndex = 0;

    this.Setup = function () {
        this.zIndex = GetTabIndex(_controlId);
    }

    this.GetClearValue = function (inputText) {
        // Remove preamble and prefix
        if (inputText.indexOf(this.prefix) == 1)
            return inputText.substring(this.prefix.length + 1, inputText.length);
        else
            return null;
    }

    this.IsMatched = function (inputText) {
        // The first char is preamble
        if (inputText.indexOf(this.prefix) == 1)
            return true;
        else
            return false;
    }

    this.GetInputElement = function () {
        var inp = document.getElementById(this.controlId);
        if (inp) {
            if (!inp.disabled && inp.style.display != "none" && !inp.readOnly) {
                return inp;
            }
        }
        return null;
    }

    this.PopulateValue = function (inputText) {
        setTimeout("document.getElementById('" + this.controlId + "').value = '" + inputText + "';" + (document.getElementById(this.controlId).onchange != null? " document.getElementById('" + this.controlId + "').onchange();": ""), 100);
    }    //PopulateValue
}

function SmartScanProcessor(_delimiters, _preambleChar, _defaultErrorLabel, _internationalErrorLabel) {
    this.defaultErrorLabel = _defaultErrorLabel;
    this.internationalErrorLabel = _internationalErrorLabel;
    this.isTypeScanner = false;
    this.delimiters = _delimiters;
    this.preambleChar = _preambleChar;
    this.templates = new Array();
    this.templatesCount = 0;
    this.inputBuffer = "";
    this.inputStarted = false;
    this.isSetupDone = false;

    this.AddTemplate = function (_controlId, _prefix, _suffix, _regExp) {
        var templ = new SmartScanTemplate(_controlId, _prefix, _suffix, _regExp);
        this.templates[this.templatesCount++] = templ;
    }

    this.Setup = function () {
        for (var i = 0; i < this.templatesCount; i++) {
            this.templates[i].Setup();
        }

        // sort templates
        var tempTemplate = null;
        for (var j = 0; j < this.templatesCount; j++) {
            for (var k = 0; k < this.templatesCount - j - 1; k++) {
                if (this.templates[k].Index > this.templates[k + 1].Index) {
                    tempTemplate = this.templates[k];
                    this.templates[k] = this.templates[k + 1];
                    this.templates[k + 1] = tempTemplate;
                }
            }
        }
    }

    this.GetMatchedTemplates = function () {
        if (!this.isSetupDone) {
            this.Setup();
            this.isSetupDone = true;
        }

        var count = 0;
        var tmplMatched = new Array();
        for (var i = 0; i < this.templates.length; i++) {
            var template = this.templates[i];
            if (template.IsMatched(this.inputBuffer)) {
                tmplMatched[count++] = template;
            }
        }
        return tmplMatched;
    }

    this.FindTargetTemplate = function (_matchedTemplates) {
        var template = null;
        if (_matchedTemplates.length == 1) {
            if (_matchedTemplates[0].GetInputElement()) {
                template = _matchedTemplates[0];
            }
        }
        else {
            var index = GetTabIndex(null); // Get tabindex of focused element
            var activeCtrl = document.activeElement;
            if (activeCtrl.type != null) {
                if (activeCtrl.style.zIndex == 0 && activeCtrl.type != "text") {
                    var ctrl = GetParentElement(null);
                    if (!activeCtrl.nextSibling) {
                        if (activeCtrl.previousSibling) {
                            var tmpCtrl = activeCtrl.previousSibling;
                            if (tmpCtrl.id != null) {
                                var tempIndex = GetTabIndex(null);
                                if (tempIndex <= index) {
                                    var nextCtrl = ctrl.nextSibling;
                                    while (nextCtrl) {
                                        if (nextCtrl.style && nextCtrl.style.zIndex != "") {
                                            index = nextCtrl.style.zIndex;
                                            break;
                                        }
                                        nextCtrl = nextCtrl.nextSibling;

                                    }
                                }
                            }
                        }
                    }
                }
            }

            var isFindTemplate = false;
            for (var i = 0; i < _matchedTemplates.length; i++) {
                if (_matchedTemplates[i].zIndex >= index) {
                    if (!_matchedTemplates[i].GetInputElement()) {
                        continue;
                    }
                    template = _matchedTemplates[i];
                    isFindTemplate = true;
                    break;
                }

            }

            if (template == null) {
                if (_matchedTemplates[0].GetInputElement()) {
                    template = _matchedTemplates[0];
                }
            }
        }
        return template;
    }

    this.Resolve = function () {
        var template = null;
        var _matchedTemplates = this.GetMatchedTemplates();
        if (_matchedTemplates.length > 0) {
            template = this.FindTargetTemplate(_matchedTemplates);
        }
        else
        {
            setTimeout("alert('" + this.defaultErrorLabel + "')", 100);
        }

        if (template) {
            if (template.GetInputElement()) {
                var valueText = template.GetClearValue(this.inputBuffer);
                template.PopulateValue(valueText);
            }
        }
    }

    this.ProcessKeyPress = function (keyCode) {
        var c = String.fromCharCode(keyCode);

        if (c != null && c != "") {
            if (c == this.preambleChar) {
                this.isTypeScanner = true;

                this.inputStarted = true;
                this.inputBuffer = c;
                //If it is necessary to see the typing string uncomment the following code
                //window.status = this.inputBuffer;

                if (this.isTypeScanner) {
                    return false;
                }
            }
            else if (String.fromCharCode(keyCode) == this.delimiters) {
                if (this.isTypeScanner) {
                    this.Resolve();

                    //If it is necessary to see the typing string uncomment the following code
                    //window.status = this.inputBuffer;
                    this.isTypeScanner = false;
                    this.inputBuffer = "";
                    if (keyCode == 9)
                        return true;
                    else
                        return false;
                }
                return true;
            }
            else {
                if (this.inputStarted) {
                    this.inputBuffer += c;
                    //If it is necessary to see the typing string uncomment the following code
                    //window.status = this.inputBuffer;
                    if (this.isTypeScanner) {
                        return false;
                    }
                }
                else
                    return true;
            }
        }
    }
}

function GetParentElement(ctrlId) {
    var currTabindex = 0;
    var theControl = ctrlId ? document.getElementById(ctrlId) : document.activeElement;
    if (theControl) {
        currTabindex = theControl.style.zIndex;
        while (!currTabindex && theControl.parentElement) {
            currTabindex = theControl.parentElement.style.zIndex;
            theControl = theControl.parentElement;
        }
    }

    return theControl;
}

function GetTabIndex(ctrlId) {
    var currTabindex = 0;
    var theControl = ctrlId ? document.getElementById(ctrlId) : document.activeElement;
    if (theControl) {
        currTabindex = theControl.style.zIndex;
        while (!currTabindex && theControl.parentElement) {
            currTabindex = theControl.parentElement.style.zIndex;
            theControl = theControl.parentElement;
        }
    }
    return currTabindex;
}

function SetupSmartScanningEvents() {
    if (document.body.attachEvent) {
        document.body.attachEvent("onkeypress", SmartScanResolver);
        document.body.attachEvent("onkeydown", SmartScanTabResolver);
    }
    else
        document.onkeypress = SmartScanResolver;
}